package com.diudiu.BinarySearch;

public class BinarySearch03 {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 6, 7, 9, 11, 24, 56, 66, 77, 88, 99, 121, 234, 345};
        int target = 1;
        int result = myBinarySearch03(array, target);
        System.out.println(result);
    }

    private static int myBinarySearch03(int[] array, int target) {
        //左边指针
        int left = 0;
        //右边指针
        int right = array.length;
        //循环条件为：左指针和右指针的元素为零
        //思想：不在while循环里面找出，循环的作用为不断缩小范围直到只剩left指向的元素时结束循环，
        //     然后再循环外面比较array[left] 是否等于 target ；是就返回 left ，不是就返回-1；
        while (right - left > 1) {
            int mid = (left + right) >>> 1;
            if (target >= array[mid]) {
                left = mid;
            } else {
                right = mid;
            }
        }
        if (array[left] == target) {
            return left;
        } else {
            return -1;
        }
    }
}
